<template>
  <PageWrapper title="">
    <XGrid 
    ref="xGrid"
      :columns="columns"
      :show-overflow="true"
      :line="true"
      :expand-all="expandAllRef"
      :stripe="false"
      :checkStrictly="true"
      is-tree
      :query-api="getListData"
      :deletes-api="deletes"
      @create="drawer.data.show = true"
      @edit="handleEdit"
      @copy="handleCopy">
      <template #topLeft2>
        <a class="btn" @click="edit" :class="{disabled:editDisabled}">编辑</a>
        <Divider type="vertical"/>
        <a @click="setAllTreeExpand">展开/收起</a>
      </template>
    </XGrid>
    <Drawer 
    :show="drawer.data.show" :is-update="drawer.data.isUpdate"
        :is-copy="drawer.data.isCopy"
        :row="drawer.data.row"
        @on-success="onSuccess"
        @on-drawer-close="onDrawerClose"/>
  </PageWrapper>
</template>
<script lang="ts" name="Menu" setup>
import { Divider } from 'ant-design-vue';
import { reactive, ref, toRaw, watchPostEffect } from 'vue';
import Drawer from './Drawer.vue';
import { columns } from './data';
import { deletes, getListData } from '/@/api/admin/menu';
import { PageWrapper } from '/@/components/Page';
import { XGrid } from '/@/components/XGrid';

const xGrid = ref();

const drawer = reactive({data: {
  show: false,
  isUpdate: false,
  isCopy: false,
  row: null,
}})

const handleEdit = (row_:any) => {
  drawer.data.show = true
  drawer.data.isUpdate = true
  drawer.data.row = row_
}

const handleCopy = (row:any) => {
  let data = toRaw(row)
  data.ID = null
  // data.path = ''+new Date().getTime()
  // data.name = ''+new Date().getTime()
  data.metaId = null
  data!.meta!.ID = null
  Object.assign(drawer.data, {show: true, isUpdate: false, isCopy: true, row: data})
}

const onDrawerClose = () => {
  Object.assign(drawer, {data: {}})
}

const onSuccess = () => {
  xGrid.value.reload()
}

const expandAllRef = ref(false)
const setAllTreeExpand = () => {
  expandAllRef.value = !expandAllRef.value
  xGrid.value.setAllTreeExpand(expandAllRef.value)
}

const outEdit = reactive({data: {
  disabled: true,
  row: null,
}})
const editDisabled = ref(true)
const edit = () => {
  handleEdit(outEdit.data.row)
}

watchPostEffect(() => {
  let list = xGrid.value.getCheckedList()
  editDisabled.value = !(list.length === 1)
  if (!editDisabled.value) {
    outEdit.data.row = toRaw(list[0])
  } else {
    outEdit.data.row = null
  }
})

</script>
